<%-- 
    Document   : post
    Created on : 21 Apr 12, 22:59:02
    Author     : hartono
--%>

<%@page import="java.util.Date"%>
<%@page import="kyakya.Util"%>
<%@page import="kyakya.User"%>
<%@page import="kyakya.manager.DBManager"%>
<%@page import="kyakya.Post"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.HashMap"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<%@include file="functions.jsp" %>
<%@include file="header.jsp" %>
<head>
    <link rel="stylesheet" type="text/css" id="style" href="css/style-form.css"></link>
    <script type="text/javascript" src="post.js"></script>
    <script type="text/javascript" src="achievement.js"></script>  
</head>

<c:choose>
    <c:when test="${cookie.username !=null}">        
        <%

            Cookie cookies[] = request.getCookies();
            Cookie myCookie = null;
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName().equals("username")) {
                        myCookie = cookies[i];
                        break;
                    }
                }
            }
            User author = DBManager.getUserByUsername(myCookie.getValue());

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                // is multipart    
                HashMap<String, String> postData = new HashMap<String, String>();
                FileItem imageFile = null;

                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items;
                try {
                    items = upload.parseRequest(request);
                    Iterator itr = items.iterator();
                    boolean valid = true;
                    StringBuilder errMsgBuilder = new StringBuilder();
                    while (itr.hasNext()) {
                        FileItem item = (FileItem) itr.next();
                        if (item.isFormField()) {
                            // form field..semua di inputkan dulu
                            if (item.getString().equals("") && !item.getFieldName().equals("tag")) {
                                // ada field yang kosong kecuali about
                                valid = valid && false;
                                errMsgBuilder.append(item.getFieldName() + " harus diisi <br/>");
                                errMsgBuilder.append(' ');
                                //out.println(item.getFieldName()+"null <br/>");
                            } else {
                                postData.put(item.getFieldName(), item.getString());
                            }
//                            out.println(item.getFieldName() + " : " + postData.get(item.getFieldName()) + " : " + item.getString() + " <br/>");
                        } else {
                            // file avatar yang diupload
                            // item.getName() = file name
                            // item.getString() = isi file                            

                            if (item.getName() == null) {
                                // avatar belum diupload                                                                
                                valid = valid && false;
                                errMsgBuilder.append("avatarnull");
                            } else {
                                // valid
                                imageFile = item;
                                postData.put(item.getFieldName(), item.getName());
                                //out.println(item.getFieldName() + " : " + postData.get(item.getFieldName()) + " <br/>");
                            }
                        }
                    }

                    // validasi isi field
                    if (valid) {
                        // semua field terisi
                        if (valid) {
                            // field sesuai
                            // konek ke database




                            Post newPost = new Post();
                            newPost.setAuthorID(author.getId());
                            String postContent = "";
                            // cek content
                            boolean useImage = false;
                            if (postData.get("media").equals("image")) {
                                useImage = true;
                            }

                            newPost.setContent(" ");
                            //
                            newPost.setTags(postData.get("tag"));
                            newPost.setTitle(postData.get("judul"));
                            Date createDate = new Date();
                            newPost.setCreateTime(Util.DateToMySQLDate(createDate));

                            if (DBManager.insertNewPost(newPost)) {
                                //out.println("insert success");

                                Post newPost2 = DBManager.getPost(postData.get("judul"), createDate);


                                // update kontent
                                if (postData.get("media").equals("link")) {
                                    postContent = "1 " + postData.get("link") + " " + postData.get("desc");
                                } else if (postData.get("media").equals("image")) {
                                    String imagePath = "upload/image/" + newPost2.getId();
                                    postContent = "2 " + imagePath;
                                } else if (postData.get("media").equals("video")) {
                                    postContent = "3 " + postData.get("vid");
                                }

                                // update konten pake query update
                                if (DBManager.editContent(newPost2.getId(), postContent)) {
                                    //out.println("edit content success");
                                }

                                // update post count user
                                if (DBManager.incrementPostUser(author.getId())) {
                                    //out.println("increment success");
                                }


                                // cek achievement

                                // if gambar then upload gambar
                                if (useImage && imageFile != null) {
                                    // upload gambar
                                    File imageFolder = new File(config.getServletContext().getRealPath("/") + "/upload/image/");
                                    if (!imageFolder.exists()) {
                                        imageFolder.mkdirs();
                                    }
                                    File imagePath = new File(config.getServletContext().getRealPath("/") + "/upload/image/" + newPost2.getId());
                                    try {
                                        imageFile.write(imagePath);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }// end upload gambar

                            } else {
                                // else, insert failed
                                //out.println("insert failed");
                            }

                        } else {
                            // isi field tidak sesuai
                        }// end if isi field sesuai

                    } else {
                        // tidak semua field terisi
                    }// end if field tidak terisi


                    // validasi selesai, sekarang navigasi
                    // 
                    if (valid) {
                        // post sukses
                        System.out.println("post sukses");
                        out.println("<script type='text/javascript'>checkAchievement(" + author.getId() + ")</script>");
        %>


        <%
        } else {
            // post gagal                                                                                                                
%>              
        <form enctype='multipart/form-data' action='post.jsp' method='post' id='dform'>
            <div class='form_box' id='posting'>
                <h1>Posting Konten</h1>
                <label>
                    <span id='judul_span' class='spanvalid' >Judul</span>
                    <input type='text' class='text' name='judul' /><br />
                </label>
                <label>
                    <span id='judul_span' class='spanvalid' >Tag</span>
                    <input type='text' class='text' name='tag' /><br />
                    Masukkan tag, pisahkan dengan koma, contoh : 'hiburan,kehidupan,tawa' <br/>
                </label>
                <div >
                    <span id='media_span' class='spanvalid'>Jenis Konten</span><br /><br />
                    <input type='radio' class='radio' name='media' value='link' onclick='radio(1)'/>Link<br />
                    <input type='radio' class='radio' name='media' value='image' onclick='radio(2)'/>Gambar<br />
                    <input type='radio' class='radio' name='media' value='video' onclick='radio(3)'/>Video<br />	
                </div>
            </div>
        </form>
        <%

                    out.println("Error, please look at these errors <br/>");
                    out.println(errMsgBuilder.toString());
                }  // end if post gagal                     

            } catch (Exception e) {
                System.out.println("post.jsp : upload parseRequest error");
                out.println("post.jsp : exception");
                e.printStackTrace();
            }

        } else {
        %>

        <form enctype='multipart/form-data' action='post.jsp' method='post' id='dform'>
            <div class='form_box' id='posting'>
                <h1>Posting Konten</h1>
                <label>
                    <span id='judul_span' class='spanvalid' >Judul</span>
                    <input type='text' class='text' name='judul' /><br />
                </label>
                <label>
                    <span id='judul_span' class='spanvalid' >Tag</span>
                    <input type='text' class='text' name='tag' /><br />
					Masukkan tag, pisahkan dengan koma, contoh : 'hiburan,kehidupan,tawa' <br/>
                </label>
                <div >
                    <span id='media_span' class='spanvalid'>Jenis Konten</span><br /><br />
                    <input type='radio' class='radio' name='media' value='link' onclick='radio(1)'/>Link<br />
                    <input type='radio' class='radio' name='media' value='image' onclick='radio(2)'/>Gambar<br />
                    <input type='radio' class='radio' name='media' value='video' onclick='radio(3)'/>Video<br />	
                </div>
            </div>
        </form>
        <%            }
        %>
    </c:when>    

    <c:otherwise>
        <div>Haven't register yet? please register at <a href="registration.jsp">here</a></div>
    </c:otherwise>
</c:choose>

<%@include file="footer.jsp" %>